package summary;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:30
 * https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
 */
public class Title113 {

    class TreeNode {
        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        List<Integer> paths = new ArrayList<>();
        dfs(root, result, paths, targetSum);
        return result;
    }

    public void dfs(TreeNode root, List<List<Integer>> result, List<Integer> paths, int targetSum){
        paths.add(root.val);
        targetSum -= root.val;
        if(root.left == null && root.right == null && targetSum == 0){
            result.add(new ArrayList<>(paths));
            return;
        }
        if(root.left != null){
            dfs(root.left, result, paths, targetSum);
            paths.remove(paths.size() - 1);
        }
        if(root.right != null){
            dfs(root.right, result, paths, targetSum);
            paths.remove(paths.size() - 1);
        }
    }
}
